<?php
namespace App\Service\Order;

use DB;

use App\Service\WdhService;

use App\Models\Goods\GoodsStore;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\Promotion\PromotionBuyLog;

use App\Models\ConfigureFunction; //功能配置表

class SecKillOrderService extends OrderService
{

    public function __construct($bill, $creator = 'system')
    {
        parent::__construct($bill, $creator);
    }

    public function submit()
    {

        $this->createGoods();

        $this->createPay();

        $this->createTrace();

        $this->createMaster();

        $max_sale_amount = $this->bill['max_sale_amount'];
        $tsid = $this->bill['goods'][0]['time_slot_id'];

        try {

            DB::beginTransaction();

            foreach ($this->insert as &$table) {

                foreach ($table as &$model) {

                    $model->save();

                    if ($model['table'] == 'bill_pay') {
                        if ($model->payTypeID == 2) { //余额
                            $balance_data = array(
                                'cardNo' => $this->cardNo,
                                'pcustID' => $this->pcustID,
                                'custID' => $this->custID,
                                'openId' => $this->openId,
                                'amount' => $model->pay_amount,
                                'password' => $this->bill['payPwd'],
                                'remark' => '订单' . $this->bill_no . '使用余额'
                            );
                            $res = WdhService::deductionBalance($balance_data);
                            if ($res['code'] != 200) {
                                throw new \Exception($res['message'], 400);
                            }
                        } elseif ($model->payTypeID == 3) { //积分
                            $points_data = array(
                                'cardNo' => $this->cardNo,
                                'pcustID' => $this->pcustID,
                                'custID' => $this->custID,
                                'openId' => $this->openId,
                                'points' => $model->pay_amount,
                                'remark' => '订单' . $this->bill_no . '使用积分'
                            );
                            $res = WdhService::deductionPoints($points_data);
                            if ($res['code'] != 200) {
                                throw new \Exception($res['message'], 400);
                            }
                        }
                    } else if ($model['table'] == 'bill_goods') {

                        $id = $this->bill['activity_id'];
                        $postID = $model->goods_postID;
                        $goods_amount = $model->goods_amount;

                        //扣减库存
                        $store_row = GoodsStore::where([
                            ['storeID', '=', $this->bill['mallID']],
                            ['product_code', '=', $model->product_code],
                            ['enableSaleAmount', '>=', $model->goods_amount],
                        ])->decrement('enableSaleAmount', $model->goods_amount);
                        if (!$store_row) {
                            throw new \Exception('商品:' . $model->goods_name . '库存不足，下单失败', 400);
                        }

                        //检查秒杀库存并扣减
                        $goods_buy_count = Redis::incrBy('SEC_KILL_BUY_NUM_' . $id . '_' . $tsid . '_' . $postID, $goods_amount);
                        if ($goods_buy_count > $max_sale_amount) {
                            Redis::decrBy('SEC_KILL_BUY_NUM_' . $id . '_' . $tsid . '_' . $postID, $goods_amount);
                            throw new \Exception('秒杀商品:' . $model->goods_name . '库存不足，下单失败', 400);
                        }

                        //查询会员购买记录
                        $buyLog = PromotionBuyLog::where([
                            'promotion_id' => $id,
                            'promotion_extend_id' => $tsid,
                            'pcustID' => $this->pcustID,
                            'postID' => $postID
                        ])->first();
                        if ($buyLog) {
                            $buy_num = $buyLog->buy_num + $goods_amount;
                            if ($buyLog->max_buy_num >= $buy_num || $buyLog->max_buy_num == 0) {
                                PromotionBuyLog::where([
                                    'promotion_id' => $id,
                                    'promotion_extend_id' => $tsid,
                                    'pcustID' => $this->pcustID,
                                    'postID' => $postID
                                ])->update(['buy_num' => $buy_num]);
                            } else {
                                throw new \Exception('秒杀商品:' . $model->goods_name . '超过会员最大购买个数，下单失败', 400);
                            }
                        }

                    }

                }

            }

            DB::commit();

            //更新会员手机，名称
            if( isset($this->bill['deliver_mobile'] , $this->bill['deliver_name']) && isMobile($this->bill['deliver_mobile']) && !empty($this->bill['deliver_name']) ){
                $deliver_data = array(
                    'cust_mobile' => $this->bill['deliver_mobile'],
                    'cust_name' => $this->bill['deliver_name']
                );
                Redis::setex('CUST_ZITI_INFO_' .  $this->pcustID, 630720000, json_encode($deliver_data, true));
            }

            //订单设置
            $bill_config = ConfigureFunction::getConfigure(21);
            $deliver_bill_create_code = 0;
            $bill_create_pickup_code = 0;
            if (isset($bill_config['configure']['deliver_bill_create_code'])) {
                $deliver_bill_create_code = $bill_config['configure']['deliver_bill_create_code'];
            }
            if (isset($bill_config['configure']['bill_create_pickup_code'])) {
                $bill_create_pickup_code = $bill_config['configure']['bill_create_pickup_code'];
            }

            //是否为虚拟商品
            $virtual_type = 0;
            if ($this->bill['goods'][0]['virtual_id']) {
                $virtual_type = 1;
            }

            if ($bill_create_pickup_code > 0) {
                if( $this->bill['sendTypeID'] == 2 || ($this->bill['sendTypeID'] == 1 && $deliver_bill_create_code == 1 ) ){
                    if ($virtual_type == 0) {
                        /**
                         * ==============start订单生码====================
                         */
                        $push_array = [
                            'call_url' => $this->bill['host'] . '/async/bill/create_bill_code.php',
                            'bill_no' => (string)$this->bill_no,
                            'pcustID' => (string)$this->pcustID,
                            'failed_url' => $this->bill['host'] . '/async/bill/create_bill_code.php?bill_no='.(string)$this->bill_no
                                .'&pcustID='.(string)$this->pcustID
                        ];
                        WdhService::asycPush($push_array);

                        /**
                         * ==============end订单生码====================
                         */
                    }
                }
            }


            //“货到付款”或者“在线支付已全付”的订单，调用拆单脚本
            if ( $this->bill['pay_type'] == 1 || ($this->bill['pay_type'] == 2 && $this->pay_status == 1) ) {

                /**
                 * ==============start调用拆单脚本====================
                 */
                $push_array = [
                    'call_url' => $this->bill['host'] . '/async/bill/bill.split.php',
                    'bill_no' => $this->bill_no,
                    'failed_url' => $this->bill['host'] . '/async/bill/bill.split.php?bill_no='.$this->bill_no
                ];

                WdhService::asycPush($push_array);

                /**
                 * ==============end调用拆单脚本====================
                 */

            }

            /**
             * ==============start推送订单创建成功消息模板====================
             */
            $push_params = array(
                'url' => $this->bill['host'] . '/wap/member/order_detail.html?id=' . $this->bill_no,
                'orderno' => $this->bill_no,
                'pcustID' => $this->pcustID,
                'refundno' => $this->bill['bill_total_amount'],
                'refundproduct' => $this->bill['bill_payable'] . '元',
            );

            //推送订单创建成功消息模板
            $push_array = array(
                'call_url' => $this->bill['host'] . '/async/message/message.php',
                'scene_id' => '1010',
                'params' => json_encode($push_params)
            );
            WdhService::sendMessage($push_array);

            /**
             * ==============end推送订单创建成功消息模板====================
             */


            /**
             * ==============start虚拟商品已付款下发送优惠券====================
             */
            if ($this->pay_status == 1 && $virtual_type == 1) {
                $virtual_array = array(
                    'call_url'   => $this->bill['host'] . '/async/bill/bill_goods_coupon.php',
                    'bill_no'   => (string)$this->bill_no,
                    'failed_url' => $this->bill['host'] . '/async/bill/bill_goods_coupon.php?bill_no='.(string)$this->bill_no
                );
                WdhService::asycPush($virtual_array);
            }

            /**
             * ==============end虚拟商品已付款下发送优惠券====================
             */


            $return_data = [
                'mallID' => $this->bill['mallID'],
                'pcustID' => $this->pcustID,
                'mallCode' => $this->bill['mallCode'],
                'bill_no' => $this->bill_no,
                'pay_amount' => $this->bill['bill_payable'],
                'pay_status' => $this->pay_status,
                'openId' => $this->bill['openId']
            ];

            return array('code' => 200, 'message' => '秒杀单保存成功', 'data' => $return_data);

        } catch (\Exception $e) {
            DB::rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                return array('code' => 500, 'message' => '系统错误');
            }
        }

    }

}